package lightswitch.code.connection;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

import lightswitch.client.code.gui.MainFrame;


public class ConnectionHelper {
    public static Socket clientSocket = null;
    private static int port = 12345;
    private static String connectionIP = "127.0.0.1";
    public static boolean flagNonQuery = true;
    
    public ConnectionHelper(){
        
    }
    
    public void setPort(int p){
        this.port = p;
    }
    
    public static boolean connect(){
        try {
            clientSocket = new Socket(connectionIP, port);
            return true;
        } catch (UnknownHostException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
        return false;
    }
    
    public boolean disConnect(){
        try {
            clientSocket.close();
            clientSocket = null;
            return true;
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
        return false;
    }
    
    public void setSocket(Socket s){
        clientSocket = s;
    }
    
    public void setConnectionIP(String ip){
        connectionIP = ip;
    }
    
    public String getConnectionIP(){
        return connectionIP;
    }
    
    public int getPort(){
        return port;
    }
    
    public boolean send(String query){
        // start thread receive
        new DataReceivingThread(clientSocket, query).start();
        return true;
    }
    
    public static boolean checkQuery(String query){
        return true;
    }

    public static void changeQueryData(QueryDataTransfering data) {
        if (data.flagError == true){
          JOptionPane.showMessageDialog(null, "Query is invalid!", "Message", 1);
          return;  
        }
        if (data.isEmpty()){
            //show dialog
            JOptionPane.showMessageDialog(null, "Result is empty!", "Message", 1);
            return;
        }
        
        MainFrame.initJTable(data);
    }

    
}
